package com.wocai.jrt.orgadmin.product.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.vteba.utils.id.ObjectId;
import com.vteba.web.action.GenericAction;
import com.vteba.web.action.JsonBean;
import com.wocai.jrt.orgadmin.product.model.ProductGroup;
import com.wocai.jrt.orgadmin.product.service.spi.ProductGroupService;
import com.wocai.jrt.orgadmin.utils.UserUtils;

/**
 * 产品组控制器
 * 
 * @author yinlei
 * @date 2016-1-4 10:56:47
 */
@Controller
@RequestMapping("/productGroup")
public class ProductGroupAction extends GenericAction<ProductGroup> {
	private static final Logger LOGGER = LoggerFactory.getLogger(ProductAction.class);

	@Inject
	private ProductGroupService productGroupServiceImpl;

	/**
	 * 获得产品组List，初始化列表页。
	 * 
	 * @param model
	 *            参数
	 * @return 产品组List
	 */
	@RequestMapping("/list")
	public String list(ProductGroup model) {
		return "productGroup/list";
	}

	/**
	 * 获得产品组List，Json格式。
	 * 
	 * @param model
	 *            参数
	 * @return 产品组List
	 */
	@ResponseBody
	@RequestMapping("/query")
	public Map<String, Object> query(@RequestBody ProductGroup model) {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			LOGGER.info("request productGroup query, param = [{}]", JSON.toJSONString(model));
			List<ProductGroup> list = new ArrayList<ProductGroup>();
			model.setOrgId(UserUtils.getOrgId());
			list = productGroupServiceImpl.pagedList(model);
			
			model.setStart(null);
			int size = productGroupServiceImpl.countBy(model);
			
			map.put("aaData", list); // 返回的数据
			map.put("iTotalRecords", size); // 总记录数
			map.put("iTotalDisplayRecords", size); // 显示的记录数
		} catch (Exception e) {
			LOGGER.error("request productGroup query error, msg = [{}]", e.getMessage());
		}
		return map;
	}

	/**
	 * 跳转到新增页面
	 * 
	 * @return 新增页面逻辑视图
	 */
	@RequestMapping("/add")
	public String add() {
		return "productGroup/add";
	}

	/**
	 * 执行实际的新增操作
	 * 
	 * @param model
	 *            要新增的数据
	 * @return 新增页面逻辑视图
	 */
	@ResponseBody
	@RequestMapping("/doAdd")
	public JsonBean doAdd(ProductGroup model) {
		JsonBean bean = new JsonBean();
		try {
			if (model.getName() != null) {
				if (model.getName().length() > 50) {
					bean.setCode(0);
					bean.setMessage("组别名称太长！");
					return bean;
				}
			} else {
				bean.setCode(0);
				bean.setMessage("组别名称不能为空！");
				return bean;
			}
			ProductGroup productGroup = new ProductGroup();
			productGroup.setId(ObjectId.get().toString());
			productGroup.setName(model.getName());
			productGroup.setNumber(0);
			productGroup.setOrgId(UserUtils.getOrgId());
			int result = productGroupServiceImpl.save(productGroup);
			if (result == 1) {
				bean.setMessage(SUCCESS);
				bean.setCode(1);
				LOGGER.info("save record success.");
			} else {
				bean.setMessage(ERROR);
				LOGGER.error("save record error.");
			}
		} catch (Exception e) {
			LOGGER.error("save record error, errorMsg=[{}].", e.getMessage());
			bean.setMessage(ERROR);
		}
		return bean;
	}

	/**
	 * 跳转到编辑信息页面
	 * 
	 * @param model
	 *            查询参数，携带ID
	 * @return 编辑页面
	 */
	@ResponseBody
	@RequestMapping("/edit/{id}")
	public JsonBean edit(@PathVariable("id") String id) {
		JsonBean jsonBean = new JsonBean();
		try {
			ProductGroup productGroup = productGroupServiceImpl.get(id);
			if (null != productGroup) {
				jsonBean.setCode(1);
				jsonBean.setMessage(SUCCESS);
				jsonBean.setData(productGroup);
			} else {
				jsonBean.setCode(0);
				jsonBean.setMessage("组别不存在！");
			}
		} catch (Exception e) {
			LOGGER.error("query record detail, errorMsg=[{}].", e.getMessage());
			jsonBean.setCode(0);
			jsonBean.setMessage(ERROR);
		}
		return jsonBean;
	}

	/**
	 * 更新产品组信息
	 * 
	 * @param model
	 *            要更新的产品组信息，含有ID
	 * @return 操作结果信息
	 */
	@ResponseBody
	@RequestMapping("/update")
	public JsonBean update(ProductGroup model) {
		JsonBean bean = new JsonBean();
		try {
			int result = productGroupServiceImpl.updateById(model);
			if (result == 1) {
				bean.setMessage(SUCCESS);
				bean.setCode(1);
				LOGGER.info("update record success.");
			} else {
				bean.setMessage(ERROR);
				LOGGER.error("update record error.");
			}
		} catch (Exception e) {
			LOGGER.error("update record error, errorMsg=[{}].", e.getMessage());
			bean.setMessage(ERROR);
		}
		return bean;
	}

	/**
	 * 删除产品组信息
	 * 
	 * @param id
	 *            要删除的产品组ID
	 */
	@ResponseBody
	@RequestMapping("/delete/{id}")
	public JsonBean delete(@PathVariable("id") String id) {
		JsonBean bean = new JsonBean();
		try {
			int result = productGroupServiceImpl.deleteProductGroupById(id);
			if (result == 1) {
				bean.setMessage(SUCCESS);
				bean.setCode(1);
				LOGGER.info("delete record success, id=[{}].", id);
			} else {
				bean.setMessage(ERROR);
				LOGGER.error("delete record error.");
			}
		} catch (Exception e) {
			LOGGER.error("delete record error, id=[{}], errorMsg=[{}].", id, e.getMessage());
			bean.setMessage(ERROR);
		}
		return bean;
	}

	/**
	 * 验证
	 * 
	 * @param productGroup
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/check")
	public boolean check(ProductGroup model, Integer type) {
		if (type == null) {
			return false;
		}
		if (model.getName() != null) {
			model.setName(model.getName().trim());
		}
		model.setOrgId(UserUtils.getOrgId());
		if (model.getId() != null) {
			// id不为空是修改
			ProductGroup productGroup = productGroupServiceImpl.get(model.getId());
			if (null == productGroup) {
				return false;
			}
			int result = productGroupServiceImpl.countBy(model);
			if (result > 1) {
				return false;
			} else if (result == 1) {
				if (type == 1) {
					if (!model.getName().equals(productGroup.getName())) {
						return false;
					}
				}
			}
		} else {
			// id为空是新增
			int result = productGroupServiceImpl.countBy(model);
			if (result > 0) {
				return false;
			}
		}
		return true;
	}

	@ResponseBody
	@RequestMapping("/newGroup")
	public JsonBean newGroup(ProductGroup model) {
		JsonBean bean = new JsonBean();

		try {
			String name = model.getName();
			if (StringUtils.isBlank(name)) {
				bean.setCode(0);
				bean.setMessage("组别名称不能为空！");
				return bean;

			} else {
				if (name.length() > 50) {
					bean.setCode(0);
					bean.setMessage("组别名称不能超过50个字符！");
					return bean;
				}
			}

			ProductGroup productGroupParam = new ProductGroup();
			productGroupParam.setName(name);
			productGroupParam.setOrgId(UserUtils.getOrgId());
			int count = productGroupServiceImpl.countBy(productGroupParam);
			if (count > 0) {
				bean.setCode(0);
				bean.setMessage("组别名称已存在！");
				return bean;
			}

			model.setId(ObjectId.get().toString());
			model.setNumber(0);
			model.setOrgId(UserUtils.getOrgId());
			int result = productGroupServiceImpl.save(model);
			if (result == 1) {
				ProductGroup pgParam = new ProductGroup();
				pgParam.setOrgId(UserUtils.getOrgId());
				List<ProductGroup> list = productGroupServiceImpl.pagedList(pgParam);

				bean.setCode(1);
				bean.setData(list);
				bean.setMessage("新增组别成功！");
				LOGGER.info("new product group success, productGroupId=[{}]", model.getId());
			} else {
				bean.setMessage("新增组别失败！");
				LOGGER.error("new product group failure");
			}
		} catch (Exception e) {
			bean.setMessage("新增组别失败！");
			LOGGER.error("new product group failure, msg=[{}]", e.getMessage());
		}

		return bean;
	}
}
